import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.io.BufferedReader;
import java.io.Console;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MCGachaUtils {

    void extractUrl(){
        try {
            ProcessBuilder builder = new ProcessBuilder(
                    "reg", "query", "\"HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\KRInstall Wuthering Waves\"", "/v", "InstallPath");
            builder.redirectErrorStream(true);
            Process process = builder.start();
            process.waitFor();
            // 读取命令输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            String installPath = null;
            while ((line = reader.readLine()) != null) {
                if (line.contains("InstallPath")) {
                    installPath = line.replace("InstallPath", "").replace("REG_SZ", "").stripLeading();
                }
            }
            String url = null;
            if (Objects.isNull(installPath)) {
                System.out.println("unable to find Wuthering Waves InstallPath");
            } else {
                File file = new File(installPath + "\\Wuthering Waves Game\\Client\\Saved\\Logs\\Client.log");
                List<String> strings = Files.readAllLines(file.toPath());
                for (int i = strings.size() - 1; i >= 0; i--) {
                    String s = strings.get(i);
                    String urlRegex = "https://aki-gm-resources\\.aki-game\\.com/aki/gacha/index\\.html\\#/record\\?[^\"\\\\]*";
                    Pattern urlPattern = Pattern.compile(urlRegex);
                    Matcher urlMatcher = urlPattern.matcher(s);

                    if (urlMatcher.find()) {
                        url = urlMatcher.group();
                        break;
                    }
                }
            }
            if (Objects.nonNull(url)) {
                System.out.println("鸣潮抽卡链接提取成功(已复制到粘贴板，如果有权限的话)");
                System.out.println(url);
                Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(url), null);
            } else {
                System.out.println("未找到有效抽卡链接，请尝试打开游戏抽卡记录窗口后过一会儿再试");
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            Console console = System.console();
            if (Objects.nonNull(console)) {
                console.readLine("按回车键退出");
            }
        }
    }

}
